package com.longrise.android.loaddata.cookie;

import android.content.Context;

import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.android.util.PreferenceUtils;

import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * Cookie管理类
 * Created by chengsan on 17/10/20.
 */

public class CookiesManager implements CookieJar
{
    private PersistentCookieStore cookieStore;
    private String cookieString;
    private final static String COOKIE_STRING_KEY = "cookieKey";
    private Context context;

    public CookiesManager(Context context)
    {
        if(null == context)
        {
            return;
        }
        this.context = context.getApplicationContext();
        this.cookieStore = new PersistentCookieStore(context.getApplicationContext());
    }

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies)
    {
        if(cookieStore == null)
        {
            return;
        }
        if (cookies != null && cookies.size() > 0)
        {
            //获取需要提交的CookieStr
            StringBuilder cookieStr = new StringBuilder();
            for (Cookie item : cookies)
            {
                cookieStore.add(url, item);
                cookieStr.append(item.name()).append("=").append(item.value()+";");
            }
            //保存字符串形式的cookie到本地
            cookieString = cookieStr.toString();
            if(null != cookieString && !cookieString.isEmpty() && context != null)
            {
                PreferenceUtils.setPrefString(LoadDataManagerFather.SP_NAME,
                        Context.MODE_PRIVATE,context,COOKIE_STRING_KEY,cookieString);
            }

        }
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url)
    {
        if(cookieStore == null)
        {
            return null;
        }
        List<Cookie> cookies = cookieStore.get(url);
        return cookies;
    }

    /**
     * 获取cookie值
     * @return
     */
    public String getCookieString()
    {
        if(cookieString != null && !cookieString.isEmpty())
        {
            return cookieString;
        }

        if(context == null)
        {
            return null;
        }
        cookieString = PreferenceUtils.getPrefString(LoadDataManagerFather.SP_NAME,
                Context.MODE_PRIVATE,context,COOKIE_STRING_KEY,null);
        return cookieString;
    }


    public void addCookie(HttpUrl url, Cookie cookie,String cookieString){
        cookieStore.add(url,cookie);
        PreferenceUtils.setPrefString(LoadDataManagerFather.SP_NAME,
                Context.MODE_PRIVATE,context,COOKIE_STRING_KEY,cookieString);
    }
}
